package com.ruoyi.web.controller.tool;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.LineSeparator;

import java.io.*;

import java.util.Iterator;
import java.util.List;

public class PdfUtils {

  private static BaseFont baseFont;

  static {
    try {
      /* 解决中文无法显示：使用iTextAsian.jar包中的字体 */
      baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    } catch (DocumentException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static Font font_normal = new Font(baseFont, 10, Font.NORMAL);
  private static Font font_bold = new Font(baseFont, 10, Font.BOLD);


  /**
   *
   * @param title 标题
   * @param time 时间段
   * @param tableArray 数据
   * @return
   * @throws DocumentException
   * @throws IOException
   */
  public static ByteArrayOutputStream createPdf(String title, String time, JSONArray tableArray, JSONArray tableTitleArray, String direction) throws DocumentException, IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    /* 第一步 创建文档实例 自定义页面大小使用 */
    Document document = new Document(PageSize.A3);
    if(StrUtil.isNotBlank(direction) && direction.equals("1")) {
      setPageSizeHen(document);
    }
    /* 第二步 获取PdfWriter实例 */
    PdfWriter pdfWriter = PdfWriter.getInstance(document, baos);
    pdfWriter.setPageEvent(new CreateHeaderFooter());
    document.setMargins(64, 64, 36, 36);
    /* 第三步 打开文档 */
    document.open();
    /* 第四步 添加段落内容 */
    Paragraph paragraph = new Paragraph(title, new Font(baseFont, 18, Font.BOLD));
    paragraph.setAlignment(Element.ALIGN_CENTER);
    /* 上一段落与下一段落的间距加大10个单位 */
    paragraph.setSpacingAfter(5);
    document.add(paragraph);
    paragraph = new Paragraph(time, new Font(baseFont, 12));
    paragraph.setAlignment(Element.ALIGN_CENTER);
    paragraph.setSpacingAfter(10);
    document.add(paragraph);
    createTable(tableArray, document, tableTitleArray);
    /* 第五部 操作完成后必须执行文档关闭操作。*/
    document.close();
    return baos;
  }

  /**
   * 创建表格
   * @param jsonArray 多个表格array
   * @param d
   * @throws DocumentException
   */
  public static void createTable(JSONArray jsonArray, Document d, JSONArray tableTitleArray) throws DocumentException {
    JSONObject jo;
    PdfPTable table;
    for (int i = 0; i < jsonArray.size(); i++) {
      jo = (JSONObject) jsonArray.get(i);
      JSONArray tableData = jo.getJSONArray("tableData");
      if(null != tableData && !tableData.isEmpty()) {
        JSONArray firstArray = tableData.getJSONArray(0);
        if(null != firstArray && !firstArray.isEmpty()) {

          try{
            Paragraph paragraph = new Paragraph((String) tableTitleArray.get(i), new Font(baseFont, 13, Font.BOLD));
            paragraph.setAlignment(Element.ALIGN_LEFT);
            /* 上一段落与下一段落的间距加大10个单位 */
            d.add(paragraph);
            Paragraph p = new Paragraph();
            p.add(new Chunk(new LineSeparator()));
            p.setSpacingAfter(20);
//            p.setSpacingBefore(10);
            d.add(p);
          } catch(Exception e) {
            e.printStackTrace();
          }
          table = new PdfPTable(firstArray.size());
          table.setSpacingAfter(20);
          System.out.println(d.getPageSize());
          table.setTotalWidth(d.getPageSize().getWidth() - 128f);
          table.setLockedWidth(true);
          Font font = font_bold;
          for (int j = 0; j < tableData.size(); j++) {
            JSONArray tableColumnData = tableData.getJSONArray(j);
            for (Object tableColumnDatum : tableColumnData) {
              PdfPCell cell = new PdfPCell(new Paragraph((String) tableColumnDatum, font));
              setCellStyle(22, cell);
              if(j != 0) {
                font = font_normal;
              } else {
                font = font_bold;
                cell.setBackgroundColor(new BaseColor(217,217,217));
              }
              table.addCell(cell);
            }
          }
          d.add(table);
        }
      }
    }
  }

  private static void setCellStyle(int height, PdfPCell cell) {
    /* 单元格高度，0时表示随内容动态显示高度 */
    cell.setVerticalAlignment(Element.ALIGN_CENTER);
    cell.setCalculatedHeight(height);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
  }

  /**
   * @Author cl
   * @Description //TODO 设置页面横向
   * @Date  2020/3/24 10:26
   * @param
   * @return
   **/
  public static void setPageSizeHen(Document document){
    //横向
    Rectangle pageSize = new Rectangle(PageSize.A3.getHeight(), PageSize.A3.getWidth());
    pageSize.rotate();
    document.setPageSize(pageSize);
  }
  /**
   * @Author cl
   * @Description //TODO 设置页面竖向
   * @Date  2020/3/24 10:26
   * @param
   * @return
   **/
  public static  void setPageSizeShu(Document document){
    //竖向
    Rectangle pageSize = new Rectangle(PageSize.A3.getWidth(), PageSize.A3.getHeight());
    pageSize.rotate();
    document.setPageSize(pageSize);
  }
}
